package com.rdk.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by Administrator on 2015/5/23.
 */
@Service
public class UploadService {

    public static final String SERVER = SystemConfig.readValue("server.path");
    public static final String PIC_SERVER = SystemConfig.readValue("pic.server.path");
    public static final String MEDIA_SERVER = SystemConfig.readValue("media.server.path");
    private final String ATTACHMENT_PATH = SystemConfig.readValue("attachment.path");

    private final HashMap<String, String> extMap = new HashMap<String, String>() {
        {
            put("image", "gif,jpg,jpeg,png,bmp");
            put("flash", "swf,flv");
            put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        }
    };

    public String saveFile(MultipartFile file) throws Exception {
        String fileType;
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        String nginx = MEDIA_SERVER;
        if (",gif,jpg,jpeg,png,bmp,".contains("," + fileExt + ",")) {
            fileType = "image";
            nginx = PIC_SERVER;
        } else if (",swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4,mov,".contains("," + fileExt + ",")) {
            fileType = "media";
            nginx = MEDIA_SERVER;
        } else {
            fileType = "file";
        }

        String timestamp = DateUtil.getCurrentDate().replace("-", "") + "/"
                + DateUtil.getCurrentTime().replace(":", "").substring(0, 2) + "/";
        String savePath = ATTACHMENT_PATH + "/" + fileType + "/" + timestamp;

        File savedir = new File(savePath);
        if (!savedir.exists()) {
            savedir.mkdirs();
        }
        String newFileName = PubFun.getUUID() + "." + fileExt;

        FileOutputStream fs = new FileOutputStream(savePath + newFileName);
        byte[] bytes = file.getBytes();
        fs.write(bytes);
        fs.close();
        return nginx + timestamp + newFileName;
    }
}
